import React, { useState, useRef, useEffect } from "react";
import _ from 'lodash'
import { Form, Input, Select, Space, Button, DatePicker, Tabs } from "antd";
import { SearchOutlined, ExclamationCircleFilled } from "@ant-design/icons";
import { apiGetCalssify, apiGetCommodityList, apiProductInfoApprove, apiProductInfoRejected } from '@/request/commodity'
import { apiGetGoodsInfoPage, apiGetGoodsInfoApprove, apiGetGoodsInfoRejected, apiGetGoodsClassifyList } from '@/request/mallManagement'
import { getDateTime3 } from '@/utils/getDate'
import ThePagination from "@/components/ThePagination";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import TheDialog from "@/components/TheDialog";
import TheImage from "@/components/TheImage";
import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import store from "@/store/store"
import "../style/style.less";

const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
const { TextArea } = Input;
let options = []
// const SearchHeader = ({ getValue }) => {
//   const formRef = useRef()
//   const [options, setOptions] = useState([])
//   useEffect(() => {
//     async function fetchData() {
//       let res = await apiGetGoodsClassifyList({
//         level: '2'
//       })//await apiGetCalssify()
//       if (res.code === 0 && res.data) {
//         let options = res.data.map(v => {
//           return {
//             value: v.goodsClassifyId,
//             label: v.goodsClassifyName
//           }
//         })
//         setOptions(options)
//       }
//     }
//     fetchData();
//   }, [])
//   const onFinish = (values) => {
//     if (values.time && values.time.length) {
//       values.createTimeStart = getDateTime3(values.time[0])
//       values.createTimeEnd = getDateTime3(values.time[1])
//     }
//     delete (values.time)
//     _.forIn(values, (v, k) => {
//       if (!v) {
//         delete (values[k])
//       }
//     })
//     getValue(values)
//   }
//   const reset = () => {
//     formRef.current.setFieldsValue({
//       goodsName: '',
//       goodsId: '',
//       classifyId: null,
//       time: []
//     })
//     getValue({})
//   };
//   return (
//     <Form layout={'inline'} ref={formRef} onFinish={onFinish}>
//       <Form.Item name={"goodsName"}>
//         <Input style={{ width: 140 }} suffix={<SearchOutlined />} placeholder={"商品名称"} />
//       </Form.Item>
//       <Form.Item name={"goodsId"}>
//         <Input style={{ width: 140 }} suffix={<SearchOutlined />} placeholder={"商品ID"} />
//       </Form.Item>
//       <Form.Item name={"classifyId"} label="所属类目">
//         <Select
//           style={{ width: 140 }}
//           options={options}
//           placeholder={"所属类目"}
//         />
//       </Form.Item>
//       <Form.Item name={"time"} label="申请时间">
//         <RangePicker />
//       </Form.Item>
//       <Form.Item>
//         <Space size="small" style={{ marginLeft: 10 }}>
//           <Button type="primary" htmlType="submit">
//             查询
//           </Button>
//           <Button onClick={reset}>重置</Button>
//         </Space>
//       </Form.Item>
//     </Form>
//   );
// };

class Examine extends React.Component {
  constructor(props) {
    super(props)
    this.queryFormRef_S = React.createRef()
    this.queryFormRef_B = React.createRef()
    this.state = {
      columnsS: [
        {
          title: "商品ID",
          dataIndex: "goodsId",
          key: "goodsId",
        },
        {
          title: "商品名称",
          dataIndex: "goodsName",
          key: "goodsName",
        },
        {
          title: "商品图片",
          dataIndex: "goodsShowImages",
          key: "goodsShowImages",
          render: (text) => {
            let arr = text.split(',')
            return <Space>
              {
                arr.map(v => {
                  return <TheImage src={v} width={80} height={80} />
                })
              }
            </Space>
          }
        },
        {
          title: "商品分类",
          dataIndex: "goodsClassifyName",
          key: "goodsClassifyName",
        },
        {
          title: "商品原价",
          dataIndex: "originalPrice",
          key: "originalPrice",
          render: (text, record) => {
            return <React.$Price price={record.originalPrice || 0} />
          }
        },
        {
          title: "商品现价",
          dataIndex: "currentPrice",
          key: "currentPrice",
          render: (text, record) => {
            return <React.$Price price={record.currentPrice || 0} />
          }
        },
        {
          title: "所属商家",
          dataIndex: "storeName",
          key: "storeName",
        },
        {
          title: "审核状态",
          render: () => {
            return <span>待审核</span>
          }
        },
        {
          title: "申请时间",
          dataIndex: "createTime",
          key: "createTime",
        },
        {
          title: "上次操作时间",
          dataIndex: "lastUpdateTime",
          key: "lastUpdateTime",
          render: (text, record) => {
            return record.lastUpdateTime ? record.lastUpdateTime : "/"
          }
        },
        {
          title: "操作人",
          dataIndex: "userName",
          key: "userName",
          render: (text, record) => {
            return record.userName ? record.userName : "/"
          }
        },
        {
          title: "操作",
          fixed: "right",
          render: (text, render) => {
            return (
              <div>
                <TheButton haspermi={['mall:examine:detail']} onClick={() => this.props.history.push(`/mall/list/detail/${render.goodsId}`)}>商品详情</TheButton>
                <TheButton haspermi={['mall:examine:pass']} onClick={() => this.cancelConfirm(render.goodsId)}>通过</TheButton>
                <TheButton haspermi={['mall:examine:reject']} onClick={() => this.setState({ visible: true,textArea:'', rejectedgoodsId: render.goodsId })}>
                  驳回
                </TheButton>
              </div>
            );
          },
        },
      ],
      dataS: [],
      columnsB: [
        {
          title: "商品ID",
          dataIndex: "goodsId",
          key: "goodsId",
        },
        {
          title: "商品名称",
          dataIndex: "goodsName",
          key: "goodsName",
        },
        {
          title: "商品图片",
          dataIndex: "goodsShowImages",
          key: "goodsShowImages",
          render: (text) => {
            let arr = text.split(',')
            return <Space>
              {
                arr.map(v => {
                  return <TheImage src={v} width={80} height={80} />
                })
              }
            </Space>
          }
        },
        {
          title: "商品分类",
          dataIndex: "goodsClassifyName",
          key: "goodsClassifyName",
        },
        {
          title: "商品原价",
          dataIndex: "originalPrice",
          key: "originalPrice",
          render: (text, record) => {
            return <React.$Price price={record.originalPrice || 0} />
          }
        },
        {
          title: "商品现价",
          dataIndex: "currentPrice",
          key: "currentPrice",
          render: (text, record) => {
            return <React.$Price price={record.currentPrice || 0} />
          }
        },
        {
          title: "所属商家",
          dataIndex: "storeName",
          key: "storeName",
        },
        {
          title: "审核状态",
          render: () => {
            return <span>未通过</span>
          }
        },
        {
          title: "审核时间",
          dataIndex: "updateTime",
          key: "updateTime",
        },
        {
          title: "原因",
          dataIndex: "dismissReason",
          key: "dismissReason",
          render: (text, rcord) => text || '无'
        },
      ],
      dataB: [],
      pageDataS: {
        pageNo: 1,
        pageSize: 10,
      },
      totalS: 0,
      pageDataB: {
        pageNo: 1,
        pageSize: 10,
      },
      totalB: 0,
      visible: false,
      reviewStatus: 'S',
      searchValue: {},
      rejectedgoodsId: '',
      newColumnsS: [],
      form_showS: true,
      searchOptionS: [
        { field: 'goodsName', label: '商品名称', placeholder: '商品名称', required: false, rules: [], type: 'Input', defaultValue: '' },
        { field: 'goodsId', label: '商品ID', placeholder: '商品ID', required: false, rules: [], type: 'Input', defaultValue: '' },
        {
          field: 'classifyId', label: '所属类目', placeholder: '所属类目', required: false, rules: [], txt: 'goodsClassifyName', value: 'goodsClassifyId', type: 'Select', options: [], api: apiGetGoodsClassifyList, params: { level: 2 }, defaultValue: ''
        },
        { field: 'time', label: '申请时间', placeholder: '申请时间', required: false, rules: [], type: 'RangePicker' },

      ],
      queryFormS: {},
      newColumnsB: [],
      form_showB: true,
      searchOptionB: [
        { field: 'storeName', label: '商品名称', placeholder: '商品名称', required: false, rules: [], type: 'Input', defaultValue: '' },
        { field: 'contactsOrMobile', label: '商品ID', placeholder: '商品ID', required: false, rules: [], type: 'Input', defaultValue: '' },
        {
          field: 'isProprietary', label: '所属类目', placeholder: '所属类目', required: false, rules: [], txt: 'goodsClassifyName', value: 'goodsClassifyId', type: 'Select', options: [], api: apiGetGoodsClassifyList, params: { level: 2 }, defaultValue: ''
        },
        { field: 'time', label: '申请时间', placeholder: '申请时间', required: false, rules: [], type: 'RangePicker' },

      ],
      queryFormB: {},
      textArea:''
    };
  }
  async componentDidMount() {
    this.onColumnsFilter_b(this.state.columnsB)
    this.onColumnsFilter_s(this.state.columnsS)
    let searchParams = store.getState().searchValue
    let { queryFormS, queryFormB, pageDataB, pageDataS, pathName } = searchParams
    console.log(queryFormS, queryFormB, pageDataS, pageDataB, pathName);
    if (searchParams && pathName == 'mallExamine') {
      this.setState({
        queryFormS, queryFormB, pageDataB, pageDataS
      }, () => {
        if (this.state.reviewStatus === 'S') {
          this[`queryFormRef_S`].onSetDefault({
            ...queryFormS
          })
        } else {
          this[`queryFormRef_B`].onSetDefault({
            ...queryFormB
          })
        }

        this.getData()
      })
    } else {
      await this.getData()

    }
  }
  async fetchData() {
    let res = await apiGetGoodsClassifyList({
      level: '2'
    })//await apiGetCalssify()
    if (res.code === 0 && res.data) {
      options = res.data.map(v => {
        return {
          value: v.goodsClassifyId,
          label: v.goodsClassifyName
        }
      })
    }
  }
  getData = async (values) => {
    const { reviewStatus } = this.state
    if (values && !_.isEmpty(values.time)) {
      values.createTimeStart = getDateTime3(values.time[0])
      values.createTimeEnd = getDateTime3(values.time[1])
    }
    this.setState({
      [`queryForm${reviewStatus}`]: values === undefined ? this.state[`queryForm${reviewStatus}`] : { ...values }
    }, async () => {
      const { pageDataS, pageDataB, queryFormS, queryFormB } = this.state
      const params = {
        pageDataS, pageDataB, queryFormS, queryFormB
      }
      store.dispatch({
        type: 'SaveSearchValues',
        data: {
          pathName: 'mallExamine',
          ...params
        }
      })
      console.log(queryFormS, queryFormB, this.state[`queryForm${reviewStatus}`]);
      const { time, ...form } = this.state[`queryForm${reviewStatus}`]
      let res = await apiGetGoodsInfoPage({ reviewStatus, ...form, ...this.state[`pageData${reviewStatus}`] })
      if (res.data && res.code === 0) {
        this.setState({
          [`data${reviewStatus}`]: res.data,
          [`pageData${reviewStatus}`]: {
            pageNo: res.pageNo,
            pageSize: res.pageSize
          },
          [`total${reviewStatus}`]: res.totalCount
        })
      }
    })






  }
  tabChange = (key) => {
    this.setState({
      reviewStatus: key
    }, () => {
      this.getData()
    })
  };
  pageChangeS = (pageNo, pageSize) => {
    this.setState({
      pageDataS: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })
  };
  pageChangeB = (pageNo, pageSize) => {
    this.setState({
      pageDataB: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })
  };
  getValue = (value) => {
    this.setState({
      searchValue: value,
      pageDataS: {
        pageNo: 1,
        pageSize: 10
      },
      pageDataB: {
        pageNo: 1,
        pageSize: 10
      }
    }, () => {
      this.getData()
    })
  }
  cancelConfirm = (goodsId) => {
    React.$confirm({
      title: "您确认通过审核本条商品吗？",
      onOk: async () => {
        await apiGetGoodsInfoApprove({ goodsId }).then(
          (res) => {
            if (res.code === 0) {
              React.$message({
                type: 'info',
                content: '审核成功'
              })
            }
          }
        )
        this.getData()
      },
    });
  };
  handleCancel = () => {
    this.setState({ visible: false, rejectedgoodsId: '' });
  };
  handleOk = async () => {
    const dismissReason = this.state.textArea
    if (!dismissReason) {
      return React.$message({
        type: 'error',
        content: '请输入驳回原因'
      })
    } else {
      let res = await apiGetGoodsInfoRejected({ goodsId: this.state.rejectedgoodsId, dismissReason })
      if (res.code === 0) {
        this.setState({ visible: false }, () => {
          React.$message({
            type: 'info',
            content: '驳回成功'
          })
          this.getData()
        });
      }
    }
  };
  onReset_s() {
    this.setState({
      queryFormS: {}
    }, () => {
      this.getData()
    })
  }
  onColumnsFilter_s(value) {
    this.setState({
      newColumnsS: value
    })
  }
  onReset_b() {
    this.setState({
      queryFormB: {}
    }, () => {
      this.getData()
    })
  }
  onColumnsFilter_b(value) {
    this.setState({
      newColumnsB: value
    })
  }
  onFormSearch_S(values){
    this.setState({
      pageDataS:{
        pageNo:1,pageSize:10
      }
    },()=>{
      this.getData(values)
    })
  }
  onFormSearch_B(values){
    this.setState({
      pageDataB:{
        pageNo:1,pageSize:10
      }
    },()=>{
      this.getData(values)
    })
  }
  render() {
    const {
      columnsS,
      columnsB,
      dataS,
      dataB,
      pageDataS,
      pageDataB,
      totalS,
      totalB,
      visible,
      form_showS, searchOptionS, newColumnsS,
      form_showB, searchOptionB, newColumnsB
    } = this.state;
    return (
      <div className="p-layout-box commodity-examine">
        {/* <div className="p-search-box">
          <SearchHeader getValue={this.getValue} />
        </div> */}
        <Tabs defaultActiveKey="S" onChange={this.tabChange}>
          <TabPane tab="待审核" key="S">
            <div className="">
              <TheQueryForm ref={(ref) => this.queryFormRef_S = ref} show={form_showS} option={searchOptionS}
                onGetValues={(values) => this.onFormSearch_S(values)}
                onReset={(values) => this.onReset_s(values)}
              >
              </TheQueryForm>
              <TheTableExtend
                columns={columnsS}
                onFormTrigger={() => this.setState({ form_showS: !this.state.form_showS })}
                onTableRefresh={() => this.getData()}
                onColumnsFilter={(value) => this.onColumnsFilter_s(value)}
              >
              </TheTableExtend>
              <TheTable
                scroll={{ x: "max-content", y: '58vh' }}
                columns={newColumnsS}
                dataSource={dataS}
              />
              <ThePagination
                pageNo={pageDataS.pageNo}
                pageSize={pageDataS.pageSize}
                total={totalS}
                pageChange={this.pageChangeS}
              />
            </div>
          </TabPane>
          <TabPane tab="未通过" key="B">
            <div className="">
              <TheQueryForm ref={(ref) => this.queryFormRef_B = ref} show={form_showB} option={searchOptionB}
                onGetValues={(values) => this.onFormSearch_B(values)}
                onReset={(values) => this.onReset_b(values)}
              >
              </TheQueryForm>
              <TheTableExtend
                columns={columnsS}
                onFormTrigger={() => this.setState({ form_showB: !this.state.form_showB })}
                onTableRefresh={() => this.getData()}
                onColumnsFilter={(value) => this.onColumnsFilter_b(value)}
              >
              </TheTableExtend>
              <TheTable
                scroll={{ x: "max-content", y: '58vh' }}
                columns={newColumnsB}
                dataSource={dataB}
              />
              <ThePagination
                pageNo={pageDataB.pageNo}
                pageSize={pageDataB.pageSize}
                total={totalB}
                pageChange={this.pageChangeB}
              />
            </div>
          </TabPane>
        </Tabs>
        <TheDialog
          title={
            <div>
              <ExclamationCircleFilled
                style={{ color: "#FAAD14", marginRight: 10 }}
              />
              输入驳回原因
            </div>
          }
          width={400}
          visible={visible}
          handleCancel={this.handleCancel}
          handleOk={this.handleOk}
        >
          <TextArea
             onChange={(e) => this.setState({
              textArea: e.target.value
            })}
            allowClear
            autoSize={{ minRows: 6, maxRows: 6 }}
            maxLength={50}
            showCount
          />
        </TheDialog>
      </div>
    );
  }
}

export default Examine;
